package com.wans.guli.search.web;

import cn.hutool.core.net.URLDecoder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wans.guli.search.server.ProductService;
import com.wans.guli.search.vo.ProductSearchParamVO;
import com.wans.guli.search.vo.ProductSearchRespVO;
import com.wans.guli.search.vo.oauth.MemberVO;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;

@Controller
public class WebIndexController {

    @Autowired
    @Qualifier("ProductByESClientServiceImpl")
    private ProductService productService;
    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping(value = {"/", "/search.html", "/list.html"})
    @SneakyThrows
    public String index(ProductSearchParamVO productSearchParamVO, Model model, HttpServletRequest httpServletRequest, HttpSession session) {
        // 修改参数
        // 解码整个查询字符串
        String decodedParams = URLDecoder.decode(httpServletRequest.getQueryString(), StandardCharsets.UTF_8);
        productSearchParamVO.setQueryString(decodedParams);

        // 获取商品信息
        ProductSearchRespVO productSearchRespVO = productService.getSkuInfoBySearchParam(productSearchParamVO);


        // 设置视图参数
        model.addAttribute("productSearchRespVO", productSearchRespVO);

        // 获取用户信息
        String loginMember = (String) session.getAttribute("loginMember");
        if (loginMember == null) {
            return "index";
        }
        MemberVO memberVO = objectMapper.readValue(loginMember, MemberVO.class);
        model.addAttribute("member", memberVO);

        return "index";
    }


    @GetMapping(value = "/list")
    @ResponseBody
    public ProductSearchRespVO list(ProductSearchParamVO productSearchParamVO) {

        // 获取商品信息
        return productService.getSkuInfoBySearchParam(productSearchParamVO);
    }
}
